package com.ruoyi.web.controller.system;

import com.aliyun.dyplsapi20170525.models.BindAxnRequest;
import com.aliyun.dyplsapi20170525.models.BindAxnResponse;
import com.ruoyi.common.core.redis.RedisCache;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysVerification;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.aliyunutils.HttpUtils;
import com.ruoyi.system.domain.vo.SyCharIdVo;
import com.ruoyi.system.domain.vo.SyPhoneVo;
import com.ruoyi.system.domain.vo.SyVirtualNumberVo;
import com.ruoyi.system.service.ISysVerificationService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 第三方验证
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/Verification")
public class SysVerificationController extends BaseController {
    @Autowired
    private ISysVerificationService iSysVerificationService;

    /**
     * 修改第三方验证
     */
    @PreAuthorize("@ss.hasPermi('system:Verification:edit')")
    @Log(title = "修改第三方验证", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody SysVerification sysVerification) {
        return toAjax(iSysVerificationService.updateVerification(sysVerification));
    }


    /**
     * 查询第三方验证
     */
    @PreAuthorize("@ss.hasPermi('system:Verification:query')")
    @Log(title = "查询第三方验证", businessType = BusinessType.UPDATE)
    @GetMapping("/getVerification")
    public AjaxResult getInfo() {
        return AjaxResult.success(iSysVerificationService.selectVerification());
    }


    /**
     * 检验身份证参数是否正确
     */
    @PostMapping("/getCheck")
    public Map getCheck(@RequestBody SyCharIdVo syCharIdVo) {
        String s = this.getcardId(syCharIdVo.getName(), syCharIdVo.getCardId(), syCharIdVo.getAppcode());
        Map<String, Object> resPart = new HashMap();
        if (StringUtils.isEmpty(s)) {
            resPart.put("code", 500);  //请充值
            resPart.put("msg", "请确认是否开通阿里云身份证校验服务，或确认Appcode是否正确");  //失败
        }
        if (StringUtils.isNotEmpty(s)) {
            JSONObject jo = JSONObject.parseObject(s);
            if (!jo.get("respCode").equals("0000")) {
                resPart.put("code", 500);  //身份校验失败
                resPart.put("msg", "请确认身份证号姓名是否正确");  //失败
            } else {
                resPart.put("code", 200);  //校验成功
                resPart.put("msg", "检验成功");  //失败
            }
        }
        return resPart;
    }

    /**
     * 身份证号验证方法
     *
     * @param nane    姓名
     * @param cardId  身份证号
     * @param appcode 阿里云身份证密钥
     * @return
     */
    public static String getcardId(String nane, String cardId, String appcode) {
        String host = "https://idenauthen.market.alicloudapi.com";
        String path = "/idenAuthentication";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("idNo", cardId);
        bodys.put("name", nane);
        String fanhui = "";
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            fanhui = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fanhui;
    }

    @Autowired
    private RedisCache redisCache;  //缓存

    /**
     * 检验手机号参数是否正确
     */
    @PostMapping("/getCheckphone")
    public Map getCheckphone(@RequestBody SyPhoneVo syPhoneVo) {
        return this.getphone(syPhoneVo);
    }

    public Map getphone(SyPhoneVo syPhoneVo) {
        HashMap hashMap = new HashMap();
        try {
            //生成验证码
            String code = UUID.randomUUID().toString().substring(0, 4);
            com.aliyun.dysmsapi20170525.Client client = createClient(syPhoneVo.getAccessKeyId(), syPhoneVo.getAccessKeySecret());
            SendSmsRequest sendSmsRequest = new SendSmsRequest().setPhoneNumbers(syPhoneVo.getPhoneNumbers()).setSignName(syPhoneVo.getSignName()).setTemplateCode(syPhoneVo.getTemplateCode()).setTemplateParam("{\"code\":\"" + code + "\"}");
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            String code1 = sendSmsResponse.getBody().getCode();
            if (code1.equalsIgnoreCase("ok")) {
                //存入redis
                redisCache.setCacheObject(syPhoneVo.getPhoneNumbers(), code);
                redisCache.expire(syPhoneVo.getPhoneNumbers(), 300l); //设置失效时间 单位秒
                //发送成功
                hashMap.put("code", 200);
                hashMap.put("msg", "短信发送成功");
            } else {
                //发送失败
                hashMap.put("code", 500);
                hashMap.put("msg", "短信发送失败，请校验阿里云参数是否正确");
            }
        } catch (Exception e) {
            hashMap.put("code", 500);
            hashMap.put("msg", "短信发送失败，请校验阿里云参数是否正确");
        }
        return hashMap;
    }

    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }


    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dyplsapi20170525.Client createClient1(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dyplsapi.aliyuncs.com";
        return new com.aliyun.dyplsapi20170525.Client(config);
    }


    /**
     * 检验虚拟号参数是否正确
     */
    @PostMapping("/getVirtualNumber")
    public Map getVirtualNumber(@RequestBody SyVirtualNumberVo syVirtualNumberVo) throws Exception {
        return this.getphoneHm(syVirtualNumberVo);
    }

    public Map getphoneHm(SyVirtualNumberVo syVirtualNumberVo) throws Exception {
        HashMap hashMap = new HashMap();
        try {
            //过期时间（分钟）
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(DateUtils.dateAddMinute(new Date(), syVirtualNumberVo.getExpiration()));
            com.aliyun.dyplsapi20170525.Client client = createClient1(syVirtualNumberVo.getAccessKeyId(), syVirtualNumberVo.getAccessKeySecret());
            BindAxnRequest bindAxnRequest = new BindAxnRequest().setPoolKey(syVirtualNumberVo.getPoolKey()) //号码池key
                    .setPhoneNoA(syVirtualNumberVo.getPhone())   //需要虚拟的手机号
                    .setExpiration(format);  //过期时间
            // 复制代码运行请自行打印 API 的返回值
            BindAxnResponse bindAxnResponse = client.bindAxn(bindAxnRequest);
            String code1 = bindAxnResponse.getBody().getCode();
            if (code1.equalsIgnoreCase("ok")) {
                //发送成功
                hashMap.put("date", bindAxnResponse.getBody().getSecretBindDTO().getSecretNo());
                hashMap.put("code", 200);
                hashMap.put("msg", "虚拟号创建成功");
            } else {
                //发送失败
                hashMap.put("code", 500);
                hashMap.put("msg", "虚拟号创建失败，请校验阿里云参数是否正确");
            }
        } catch (Exception e) {
            hashMap.put("code", 500);
            hashMap.put("msg", "虚拟号创建失败，请校验阿里云参数是否正确");
        }
        return hashMap;
    }
}
